#!/bin/bash


abspath="$(realpath $0)"
basedir="$(dirname ${abspath})"

build_dir="build"

account_key="account.key"
domain_key="domain.key"
domain="$1"
domain_csr="${build_dir}/${domain}.csr"
domain_crt="${build_dir}/${domain}.crt"
acme_dir="${basedir}/challenges"
ngx_conf="ngx_conf"
acme_tiny_url="https://raw.githubusercontent.com/diafygi/acme-tiny/master/acme_tiny.py"


function gen_csr(){
    if [ ! -f "${account_key}" ];then
        openssl genrsa 4096 > "${account_key}"
    fi
    
    if [ ! -f "${domain_key}" ];then
        openssl genrsa 4096 > "${domain_key}"
    fi
    
    if [ ! -f "${domain_csr}" ];then
        openssl req -new -sha256 -key "${domain_key}" -subj "/CN=${domain}" > "${domain_csr}"
    fi
}

function ngx_conf(){
    mkdir -p "${ngx_conf}"
    if [ -f "acme.conf" ];then
        sed 's/domain/'${domain}'/g' acme.conf > "${ngx_conf}/${domain}.conf"
        sed -i 's#acmedir#'"${acme_dir}/"'#g' "${ngx_conf}/${domain}.conf"
        echo "Warning: you need config nginx acme by manual."
    else
        echo "Warning: you need config nginx acme by manual."
    fi
}

function get_ssl(){
    if [ ! -f "acme_tiny.py" ];then
        echo "Error: not found the acme_tiny.py file"
        exit 1
    fi
    mkdir -p "${acme_dir}"
    python acme_tiny.py --account-key "${account_key}" --csr "${domain_csr}" --acme-dir "${acme_dir}/" > "${domain_crt}"
}


function main() {
    cd "${basedir}"
    mkdir -p "${build_dir}"
    gen_csr
    ngx_conf
    get_ssl
}

if [ $# -ne 1 ];then
    echo "Usage: $0 <domain>"
else
    main
fi